package com.caiwangdai.app.backend.cookie;

import android.content.Context;
import android.os.Build;
import android.webkit.CookieSyncManager;


import java.util.List;

import okhttp3.Cookie;

/**
 * @author 艹羊
 * @project Checaiduo_Android
 * @date 2017/6/9 下午1:52
 * @description
 */

public class CookieCenter {

    private CookieCenter() {
    }

    public static CookieCenter getInstance() {
        return CookieCenter.Holder.INSTANCE;
    }

    public static class Holder {
        public static CookieCenter INSTANCE = new CookieCenter();

    }


    /**
     * @param context
     * @return url
     * @description 同步客户端Cookie
     * @remark
     */
    public void synCookies(Context context, String url) {
        PersistentCookieStore cookieStore = new PersistentCookieStore(context);

        CookieSyncManager.createInstance(context);
        android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.removeAllCookie();

        List<Cookie> cookies = cookieStore.getCookies();

        for (Cookie cookie : cookies) {
            // cookies是在OKHttp中获得的cookie
            cookieManager.setCookie(url, cookie.name() + "=" + cookie.value());
        }

        if (Build.VERSION.SDK_INT < 21) {
            CookieSyncManager.getInstance().sync();
        } else {
            android.webkit.CookieManager.getInstance().flush();
        }
    }

}
